<template>
  <div style="height:100%;width:100%;position:relative;">
      <div class="pagetop">
          <div style="width:100%;">
              <el-col>
                  <div ref="buttondiv">
                      <vxe-toolbar>
                          <template v-slot:buttons style="width:100%">
                              <table style="width:100%">
                                  <tr>
                                      <td>
                                          <table>
                                              <tr>
                                                  <td>检验仪器</td>
                                                  <td>
                                                      <rm-ddl-instrument :appendtobody="true" @change="labinstrumentchange" v-model="labinstrumentval" width="180px" :clearable="false" defaultflag="1" ref="instrinput"></rm-ddl-instrument>
                                                  </td>
                                                  <td>快速查询</td>
                                                  <td>
                                                      <el-input style="width:180px" v-model="searchtext" placeholder="请输入通道号或对应报告项目" @keyup.enter.native="listSearch"></el-input>
                                                  </td>
                                                  <td>结果查询日期区间</td>
                                                  <td colspan="2">
                                                      <el-date-picker v-model="datetime1" type="date" align="right" value-format="yyyy-MM-dd HH:mm:ss" size="mini" placeholder="开始日期" :clearable="false" style="width:110px"></el-date-picker> 至
                                                      <el-date-picker v-model="datetime2" type="date" align="right" value-format="yyyy-MM-dd HH:mm:ss" size="mini" placeholder="结束日期" :clearable="false" style="width:110px"></el-date-picker>
                                                  </td>
                                                  <td colspan="2">
                                                      <el-checkbox v-model="showunitreqonly" @change="showunitchange">仅显示仪器入库报告单元的项目</el-checkbox>
                                                      <el-checkbox v-model="germflag" @change="germchange">细菌模式</el-checkbox>
                                                  </td>

                                              </tr>
                                          </table>
                                      </td>
                                  </tr>
                                  <tr>
                                      <td style="text-align:right">
                                          <div style="text-align:right;width:100%">
                                              <table style="width:100%">
                                                  <tr>
                                                      <td style="align:right">
                                                          <el-button @click="FindInstrItem()" icon="el-icon-search">查询(F5)</el-button>
                                                          <el-button @click="CopyShow()" icon="el-icon-document" v-has="'PADD'">复制</el-button>
                                                          <el-button @click="OpenDialog('add')" icon="el-icon-plus" v-has="'PADD'">新增(F6)</el-button>
                                                          <el-button @click="OpenDialog('del')" icon="el-icon-delete" v-has="'PDELETE'">删除(F3)</el-button>
                                                          <el-button @click="SaveUpdate()" icon="el-icon-document" v-has="'PMODIFY'">保存(F8)</el-button>
                                                          <el-button @click="OpenDialog('nulldel')" icon="el-icon-news">删除对应报告项目为空的数据</el-button>
                                                          <el-button @click="OpenResDialog()" icon="el-icon-news">不同标本结果调整系数</el-button>
                                                          <el-button @click="AutodualVisible=true" icon="el-icon-news">智能设定双工</el-button>
                                                          <el-button @click="ExportFile()" icon="el-icon-document">导出</el-button>
                                                          <el-button @click="ImportFile()" icon="el-icon-document">导入</el-button>
                                                      </td>
                                                  </tr>
                                              </table>
                                          </div>
                                      </td>
                                  </tr>
                              </table>
                          </template>
                      </vxe-toolbar>
                  </div>
              </el-col>
          </div>
      </div>
      <div class="pagecenter">
          <rm-layout-right splitcolor="#FFFFFF" movingcolor="#FFFFFF" :splitwidth=5 :fixsize=400>
              <div ref="xTableDiv" style="height:100%;">
                  <vxe-table :data="list" :loading="loading" :select-config="selectConfig" :row-class-name="RowClass" @current-change="currentChangeEvent" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: false, showIcon: false }" :sort-config="{trigger: 'cell'}" border fit height="auto" header-align="center" highlight-current-row highlight-hover-row ref="xTable" resizable show-header-overflow="tooltip" show-overflow="tooltip" size="mini">
                      <vxe-table-column field="interno" title="通道号" :edit-render="{name: 'input', autoselect: true, events: { change: InternoChange }}" width="100px" sortable></vxe-table-column>
                      <vxe-table-column field="rptitemshow" title="对应报告项目" :edit-render="{name: 'input', autoselect: true}" width="200px" sortable>
                          <template v-slot:edit="{ row }">
                              <el-input @dblclick.native="dialogRptVisible=true,tempRptItem=row,$nextTick(() => {$refs.rptdialog.$refs.qcodeinput.focus();});" @keyup.space.native="dialogRptVisible=true,tempRptItem=row,$nextTick(() => {$refs.rptdialog.$refs.qcodeinput.focus();});" v-model="row.rptitemshow" @change="RptChange($event,row)" style="width:100%;height:20px" size="mini" :autofocus="true" readonly clearable></el-input>
                          </template>
                      </vxe-table-column>
                      <vxe-table-column field="dual_use" title="双工" :edit-render="{name: 'select', options: [{label:'是',value:'1'},{label:'否',value:'0'}]}" width="60px" align="center" sortable></vxe-table-column>
                      <vxe-table-column field="result_ratio" title="调整系数" :edit-render="{name: 'input', autoselect: true}" width="80px"></vxe-table-column>
                      <vxe-table-column field="result_add" title="调整差值" :edit-render="{name: 'input', autoselect: true}" width="80px"></vxe-table-column>
                      <vxe-table-column field="testmethod" title="测试方法" :edit-render="{name: 'input', autoselect: true}" width="100px"></vxe-table-column>
                      <vxe-table-column field="hr_flag" title="结果互认" :edit-render="{name: 'input', autoselect: true}" width="80px"></vxe-table-column>
                      <vxe-table-column field="stopflag" title="停用" width="50px" align="center" sortable>
                          <template v-slot="{ row }">
                              <el-checkbox true-label="1" false-label="0" v-model="row.stopflag"></el-checkbox>
                          </template>
                      </vxe-table-column>
                      <vxe-table-column field="lastusetime" title="最后使用时间" width="120px" sortable></vxe-table-column>
                      <vxe-table-column field="dec_digits1" title="结果1保留位数" :edit-render="{name: 'select', options: $opt.dec_digitsOption}" width="100px" align="center" sortable>
                      </vxe-table-column>
                      <vxe-table-column field="dec_digits2" title="结果2保留位数" :edit-render="{name: 'select', options: $opt.dec_digitsOption}" width="100px" align="center" sortable>
                      </vxe-table-column>
                      <vxe-table-column field="dec_digits3" title="结果3保留位数" :edit-render="{name: 'select', options: $opt.dec_digitsOption}" width="100px" align="center" sortable>
                      </vxe-table-column>
                  </vxe-table>
              </div>
              <template v-slot:fix>
                  <div style="height:100%">
                      <vxe-table :data="tableInstrData" :loading="loading" :row-class-name="rowClassName" :select-config="selectConfig" border fit height="auto" header-align="center" highlight-current-row highlight-hover-row ref="tableInstrdata" resizable show-header-overflow="tooltip" show-overflow="tooltip" size="mini" stripe>
                          <vxe-table-column :field="items.field" :key="items.field" :title="items.title" :width="items.width" v-for="items in tableInstrColumn"></vxe-table-column>
                      </vxe-table>
                  </div>
              </template>
          </rm-layout-right>
      </div>
      <el-dialog v-el-drag-dialog :close-on-click-modal="false" :title="dialogtitle" :visible.sync="dialogForm" @close="CancelTips()" v-if="dialogif" width="650px">
          <el-form :inline="true" :model="InstrItem" @submit.native.prevent label-width="auto" ref="form" style="border:1px solid #ccc">
              <table>
                  <tr>
                      <td>仪器ID</td>
                      <td>
                          <el-input style="width:100%;" v-model="InstrItem.instrid" disabled></el-input>
                      </td>
                      <td>通道号</td>
                      <td>
                          <el-input style="width:100%;" v-model="InstrItem.interno" ref="inputinter" @keyup.enter.native="autofocusEvent($event,'inter')"></el-input>
                      </td>
                  </tr>
                  <tr>
                      <td>对应报告报告项目</td>
                      <td>
                          <rm-ddl-rptitem prgno="LIS141" :appendtobody="true" :rptunitid="rptunitid" :rptunitdisabled="showunitreqonly" :germmode="germflag" v-model="InstrItem.rpt_itemcode" @change="RptChangeEvent" ref="inputrptitem" @keyup.enter.native="autofocusEvent($event,'rptitem')" v-if="dialogForm"></rm-ddl-rptitem>
                      </td>
                      <td></td>
                      <td>
                          <el-checkbox v-model="InstrItem.dual_use" true-label="1" false-label="0" @change="dualchange">双工使用</el-checkbox>
                      </td>
                  </tr>
                  <tr>
                      <td>结果调整系数</td>
                      <td>
                          <el-input style="width:100%;" v-model="InstrItem.result_ratio" ref="inputresratio" @keyup.enter.native="autofocusEvent($event,'ratio')"></el-input>
                      </td>
                      <td>结果调整差值</td>
                      <td>
                          <el-input style="width:100%;" v-model="InstrItem.result_add" ref="inputresadd" @keyup.enter.native="autofocusEvent($event,'add')"></el-input>
                      </td>
                  </tr>
                  <tr>
                      <td>测试方法</td>
                      <td>
                          <el-input style="width:100%;" v-model="InstrItem.testmethod" ref="inputmethod" @keyup.enter.native="autofocusEvent($event,'method')"></el-input>
                      </td>
                  </tr>
              </table>
          </el-form>
          <div style="text-align:right;padding-top:5px">
              <el-button @click="CommitTips()">确定</el-button>
              <el-button @click="dialogForm=false">取消</el-button>
          </div>
      </el-dialog>

      <el-dialog v-el-drag-dialog :close-on-click-modal="false" title="仪器项目根据标本类型调整系数" :visible.sync="dialogResForm" width="800px">
          <div>
              <table>
                  <tr>
                      <td>检验仪器</td>
                      <td>
                          <el-input v-model="nowinstrument" width="200px" disabled=""></el-input>
                      </td>
                      <td>报告项目</td>
                      <td>
                          <el-input disabled style="width:100%;" v-model="InstrItem.rptitemshow"></el-input>
                      </td>
                      <td>
                          <el-button icon="el-icon-plus" @click="AddRecord()">新增</el-button>
                      </td>
                      <td>
                          <el-button icon="el-icon-delete" @click="DelRecord()">删除</el-button>
                      </td>
                      <td>
                          <el-button icon="el-icon-news" @click="SaveSeries()">保存</el-button>
                      </td>
                  </tr>
              </table>
          </div>
          <div>
              <vxe-table :data.sync="tableDataRes" :edit-config="{trigger: 'click', mode: 'cell',showStatus: true}" :mouse-config="{selected: true}" :select-config="selectConfig" height="350px" highlight-current-row highlight-hover-row resizable show-header-overflow="tooltip" show-overflow="tooltip" header-align="center" :loading="loading" size="mini" stripe ref="ResNum">
                  <vxe-table-column field="specimen_code" title="标本类型">
                      <template v-slot="{ row,rowIndex }">
                          <rm-ddl-common :appendtobody="true" datatype="specimenaddall" dataname="标本类型" v-model="row.specimen_code" @change="SpecChange($event,row)" :readonly="true"></rm-ddl-common>
                      </template>
                  </vxe-table-column>
                  <vxe-table-column field="result_ratio" title="结果调整系数" :edit-render="{name: 'input'}"></vxe-table-column>
                  <vxe-table-column field="result_add" title="结果调整差值" :edit-render="{name: 'input'}"></vxe-table-column>
                  <vxe-table-column field="specimencode" title="标本类型代码"></vxe-table-column>
              </vxe-table>
          </div>
      </el-dialog>
      <el-dialog title="提示" :visible.sync="DeldialogVisible" width="30%">
          <div class="el-message-box__status el-icon-warning"></div>
          <div class="el-message-box__message" style="padding-top:24px">
              <p>确定要删除仪器通道号记录<span style="color:red;font-weight:bold">{{tempinterno}}</span>吗?</p>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button @click="CommitTips()">确 定</el-button>
              <el-button @click="CancelTips()">取 消</el-button>
          </span>
      </el-dialog>
      <el-dialog title="提示" :visible.sync="NullDeldialogVisible" width="30%">
          <div class="el-message-box__status el-icon-warning"></div>
          <div class="el-message-box__message" style="padding-top:24px">
              <p>确定要删除此报告单元<span style="color:red;font-weight:bold">{{labinstrumentname}}</span>下所有未对应报告项目的仪器通道号记录吗?</p>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button @click="CommitTips()">确 定</el-button>
              <el-button @click="CancelTips()">取 消</el-button>
          </span>
      </el-dialog>
      <el-dialog title="提示" :visible.sync="AutodualVisible" width="30%">
          <div class="el-message-box__status el-icon-warning"></div>
          <div class="el-message-box__message" style="padding-top:24px">
              <p>您是否要系统智能设定所有项目的双工使用情况</p>
          </div>
          <span slot="footer" class="dialog-footer">
              <el-button @click="dualsort()">确 定</el-button>
              <el-button @click="AutodualVisible=false">取 消</el-button>
          </span>
      </el-dialog>

      <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="报告项目" :visible.sync="dialogRptVisible" v-if="dialogRptVisible">
          <rm-pop-rptitem prgno="LIS141" :rptunitid="myrptunitid" :rptunitdisabled="showunitreqonly" :germmode="germflag" @selitem="addrptitem" @cancel="dialogRptVisible = false,$refs.xTable.setActiveCell($refs.xTable.getCurrentRow(), 'rptitemshow')" ref="rptdialog"></rm-pop-rptitem>
      </el-dialog>

      <el-dialog v-el-drag-dialog :append-to-body="true" :close-on-click-modal="false" title="复制项目" :visible.sync="dialogCopyVisible">
          <table style="width:100%">
              <tr>
                  <td style="text-align:left">
                      当前仪器
                  </td>
                  <td>
                      请选择要复制的来源仪器
                  </td>
              </tr>
              <tr>
                  <td style="text-align:left">
                      {{ copytoinstrid }}
                      <!-- <el-input disabled v-model="copytoinstrid"></el-input> -->
                  </td>
                  <td style="text-align:left">
                      <rm-ddl-instrument :appendtobody="true" v-model="targetinstrid" width="180px" :clearable="false"></rm-ddl-instrument>
                  </td>
              </tr>
              <tr>
                  <td style="text-align:right" colspan="2">
                      <el-button @click="CopyInstr()">确 定</el-button>
                      <el-button @click="dialogCopyVisible = false">取消</el-button>
                  </td>
              </tr>
          </table>
      </el-dialog>
  </div>
</template>


<script>
import { Promise } from "q";
import { invalid } from "moment";
import XEUtils from "xe-utils";
export default {
  name: "LIS141",
  data() {
      return {
          DelIndex2: -1,
          loading: false,
          showunitreqonly: true,
          germflag: false,
          labinstrumentval: "",
          labinstrumentname: "",
          buttonwidth: "",
          rptunitid: "",
          myrptunitid: "",
          InstrDataFirstLoad: true,
          dialogif: false,
          dialogForm: false,
          dialogtitle: "",
          dialogResForm: false,
          DeldialogVisible: false,
          NullDeldialogVisible: false,
          AutodualVisible: false,
          actionflag: "",
          DelIndex: -1,
          FirstLoadingItem: true,
          FirstLoadingData: true,
          tempRowIndex: -1,
          isFirstLoading: false,
          nowinstrument: "",
          tempinterno: "",
          AddArray: "",
          searchtext: "",
          txtdelelinterno: "",
          NewArr: [],
          tempdata2: [],
          UpdateArr: [],
          tableData: [],
          tableColumn: [],
          tableInstrData: [],
          list: [],
          tableInstrColumn: [],
          tableDataRes: [],
          InstrItem: {},
          tempInstrItem: {},
          leftselectrow: "",
          selectConfig: { tigger: "row" },
          datetime1: "",
          datetime2: "",
          //报告弹窗
          dialogRptVisible: false,
          tempRptItem: {},
          dialogCopyVisible: false,
          copytoinstrid: "1",
          targetinstrid: "1",
      };
  },
  computed: {},
  created() {
      this.InitPageData();
  },
  watch: {
      searchtext(val) {
          var length = this.tableData.length;
          if (this.AddArray.length > 0) {
              this.AddArray.length = 0;
          }
          this.$nextTick(() => {
              var row = this.$refs.xTable.getCurrentRow();
              var aftersearchrow = this.$refs.xTable.tableData.filter((item) => {
                  return item.interno == row.interno;
              });
              if (aftersearchrow.length == 0) {
                  if (this.$refs.xTable.tableData.length > 0) row = this.$refs.xTable.tableData[0];
                  if (row.interno) {
                      this.$refs.xTable.setCurrentRow(row);
                      this.tempRowIndex = this.$refs.xTable.getRowIndex(row);
                  }
              }
          });
      },
  },
  mounted() {},
  updated() {
      this.getButtonWidth();
  },
  methods: {
      //格式化表格数据
      formatFun({ cellValue, column, row }) {
          if (column.property == "sampledate") {
              try {
                  let formatdate = XEUtils.toDateString(cellValue, "yyyy-MM-dd");
                  return formatdate;
              } catch {}
          } else if (column.property == "rpt_itemcode") {
              try {
                  let rpt_item = this.lab_rptitemoption.find((m) => m.rpt_itemcode == cellValue);
                  if (rpt_item != undefined && rpt_item != null) {
                      return rpt_item.itemcode_en + " " + rpt_item.rpt_itemname;
                  }
                  return cellValue;
              } catch {}
          } else if (column.property == "rptunitid") {
              try {
                  let rptunitna = this.lab_rptunitoption.find((m) => m.rptunitid == cellValue);
                  if (rptunitna != undefined && rptunitna != null) {
                      return rptunitna.rptunitname + "[" + cellValue + "]";
                  }
                  return cellValue;
              } catch {}
          }
      },
      InitPageData() {
          this.datetime1 = this.$pub.InitDateTime2(0).datefrom;
          this.datetime2 = this.$pub.InitDateTime2(0).dateto;
          //this.FindInstrItem();
          //this.FindInstrData();
      },
      currentChangeEvent({ row }) {
          this.InstrItem = row;
          this.tempInstrItem = JSON.parse(JSON.stringify(row));
          this.tempinterno = row.interno;
          this.tempRowIndex = this.$refs.xTable.getRowIndex(row);
          this.FindInstrData();
      },
      getButtonWidth() {
          if (this.$refs.buttondiv) {
              this.buttonwidth = this.$refs.buttondiv.offsetWidth - 200 + "px";
          }
      },
      rowClassName({ row, rowIndex }) {
          if (this.NewArr.indexOf(row.instrid + "") > -1) {
              return "Add";
          }
          if (this.UpdateArr.indexOf(row.instrid + "") > -1) {
              return "Update";
          }
          // if (rowIndex == 0) {
          //     return "rm-cancel"; //作废
          // } else if (rowIndex == 1) {
          //     return "rm-disable"; //禁用
          // } else if (rowIndex == 2) {
          //     return "rm-readonly"; //只读
          // } else if (rowIndex == 3) {
          //     return "rm-alert"; //警告
          // }
      },
      RowClass({ row }) {
          let isDirty = this.$refs.xTable.hasRowChange(row);
          if (isDirty) {
              return "row-modify";
          }
          if (this.$refs.xTable.hasRowInsert(row)) {
              return "row-new";
          }
          if (row.dual_use == "1") {
              return "DualRow";
          }
      },
      labinstrumentchange(code, name, row) {
          this.labinstrumentval = code;
          this.labinstrumentname = name;
          this.rptunitid = row.rptunitid;
          if (this.showunitreqonly) {
              this.myrptunitid = this.rptunitid;
          } else {
              this.myrptunitid = "";
          }
          this.nowinstrument = row.instrname;
          this.NewArr = [];
          this.UpdateArr = [];
          this.FindInstrItem();
          this.tableInstrData = [];
      },
      OpenDialog(flag) {
          this.actionflag = flag;
          var actionflag = ""; //新增通道号时清空右侧列表
          if (flag == "add") {
              this.InstrItem = { interno: "", rpt_itemcode: "", dual_use: "0", result_ratio: "1.0", result_add: "0.0" };

              this.tableInstrData = [];
              this.$refs.xTable.insertAt(this.InstrItem, -1).then((res) => {
                  this.$refs.xTable.setCurrentRow(res.row).then(() => {
                      this.$refs.xTable.scrollToRow(res.row);
                  });
              });
              // this.dialogtitle = "新增仪器通道号项目对照";
              // this.dialogif = true;
              // this.dialogForm = true;
              // actionflag = "add";
              // this.$nextTick(() => {
              //     this.$refs.inputinter.focus();
              // });
          }
          if (flag == "update") {
              if (this.InstrItem.instrid) {
                  this.FindUpdataInstrItem();
                  //this.tempInstrItem = this.InstrItem;
                  this.dialogtitle = "修改仪器通道号项目对照";
                  this.dialogif = true;
                  this.dialogForm = true;
                  actionflag = "update";
                  this.tempRowIndex = this.$refs.xTable.getRowIndex(this.tempInstrItem);
                  this.$nextTick(() => {
                      this.$refs.inputinter.focus();
                  });
              } else {
                  this.$message({
                      message: "未选中要修改项目!",
                      type: "warn",
                  });
              }
          }
          if (flag == "del") {
              var row = this.$refs.xTable.getCurrentRow();
              if (row) {
                  this.$confirm("确定要删除仪器通道号记录" + row.interno + "吗？",{
                      confirmButtonText: "确定(Y)",
                      cancelButtonText: "取消(N)",
                      type: "warning",
                  }).then(() => {
                      this.SaveRecord("del");
                  });
              } else {
                  this.$confirm("请选择要删除的行!");
              }
          }
          if (flag == "nulldel") {
              this.NullDeldialogVisible = true;
              actionflag = "nulldel";
          }
      },
      OpenResDialog() {
          this.FindDilution();
          this.dialogResForm = true;
          this.nowinstrument = this.$refs.instrinput.seloptions.filter((item) => item.instrid == this.labinstrumentval)[0].instrname;
          this.DelIndex = -1;
      },
      FindInstrData(instridval) {
          var mintime = this.datetime1;
          var maxtime = this.datetime2;
          var instrid = this.labinstrumentval;
          if (instridval) instrid = XEUtils.clone(instridval, true);
          var interno = this.InstrItem.interno;
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "querydetail",
                      instrid: instrid,
                      interno: interno,
                      datebegin: mintime,
                      dateend: maxtime,
                  },
              })
              .then((res) => {
                  this.tableInstrData = res.Data;
                  var collist = [];
                  if (this.FirstLoadingData) {
                      for (let i = 0, len = res.Cols.length; i < len; i++) {
                          const item = res.Cols[i];
                          let colitem = {};
                          colitem = {
                              field: item.field,
                              title: item.title,
                              width: "120px",
                          };
                          collist.push(colitem);
                      }
                      this.tableInstrColumn = collist;
                      this.FirstLoadingData = false;
                  }
              });
      },
      FindInstrItem(instrid) {
          var tmpdiff = XEUtils.getDateDiff(this.datetime1, this.datetime2);
          if (tmpdiff.done && (tmpdiff.yyyy > 0 || tmpdiff.MM > 0 || tmpdiff.dd > 6)) {
              this.$alert("查询日期区间最大为7天，请修改区间再次查询。", "提示", {
                  confirmButtonText: "确定",
                  type: "warning",
              });
              return false;
          }
          var instrval = this.labinstrumentval;
          if (instrid) instrval = XEUtils.clone(instrid, true);
          var onlyrptunit = this.showunitreqonly ? "1" : "0";
          this.DelIndex2 = -1;
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "query",
                      instrid: instrval,
                      onlyrptunit: onlyrptunit,
                  },
              })
              .then((res) => {
                  var tempdata = res.Data;
                  for (let i = 0, len = tempdata.length; i < len; i++) {
                      tempdata[i].dual_useCH = tempdata[i].dual_use > 0 ? "是" : "否";
                  }
                  if (this.FirstLoadingItem) {
                      var collist = [];
                      for (let i = 0, len = res.Cols.length; i < len; i++) {
                          const item = res.Cols[i];
                          let colitem = {};
                          colitem = {
                              field: item.field == "dual_use" ? "dual_useCH" : item.field,
                              title: item.title,
                              width: item.width,
                          };
                          collist.push(colitem);
                      }
                      this.tableColumn = collist;
                      if (this.InstrItem) this.$refs.xTable.setCurrentRow(this.InstrItem);
                      this.FirstLoadingItem = false;
                  }
                  this.tableData = tempdata;
                  this.listSearch();
                  this.tempdata2 = JSON.parse(JSON.stringify(res.Data));
              });
      },
      FindDilution() {
          var instrid = this.labinstrumentval;
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "querydilution",
                      instrid: instrid,
                      rpt_itemcode: this.InstrItem.rpt_itemcode,
                  },
              })
              .then((res) => {
                  var resdata = res.Data;
                  if (resdata) {
                      for (let i = 0, len = resdata.length; i < len; i++) {
                          resdata[i].specimencode = resdata[i].specimen_code;
                      }
                  }

                  this.tableDataRes = resdata;
              });
      },
      FindUpdataInstrItem() {
          var instrid = this.labinstrumentval;
          var interno = this.InstrItem.interno;
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "queryforupdateinstritem",
                      instrid: instrid,
                      interno: interno,
                  },
              })
              .then((res) => {
                  this.InstrItem = res.Data[0];
                  this.tempInstrItem = JSON.parse(JSON.stringify(res.Data[0]));
                  this.rptunitid = res.Data[0].rptunitid;
                  if (this.showunitreqonly) {
                      this.myrptunitid = this.rptunitid;
                  } else {
                      this.myrptunitid = "";
                  }
              });
      },
      AddRecord() {
          var row = { result_ratio: 1, result_add: 0 };
          this.$refs.ResNum.insertAt(row, -1);
      },
      DelRecord() {
          var delrow = this.$refs.ResNum.getCurrentRow();
          if (this.DelIndex < 0) this.DelIndex = this.$refs.ResNum.getRowIndex(delrow);
          this.$refs.ResNum.remove(delrow);
          if (this.DelIndex > -1) {
              if (this.$refs.ResNum.getTableData().fullData.length > this.DelIndex) this.DelIndex = this.DelIndex;
              else this.DelIndex = this.DelIndex - 1;
              if (this.DelIndex >= 0) {
                  var selectrow = this.$refs.ResNum.getTableData().fullData[this.DelIndex];
                  this.$refs.ResNum.setCurrentRow(selectrow);
              }
          }
      },
      SaveRecord(action) {
          var returnInstrItem = {
              instrid: this.labinstrumentval,
              interno: this.InstrItem.interno,
              rpt_itemcode: this.InstrItem.rpt_itemcode,
              dual_use: this.InstrItem.dual_use,
              result_ratio: this.InstrItem.result_ratio - 0,
              result_add: this.InstrItem.result_add,
              testmethod: this.InstrItem.testmethod,
          };
          if (action == "del") {
              var delrow = this.$refs.xTable.getCurrentRow();
              if (this.DelIndex2 < 0) this.DelIndex2 = this.$refs.xTable.getRowIndex(delrow);
              if (this.DelIndex2 > -1) {
                  if (this.$refs.xTable.getTableData().fullData.length > this.DelIndex2) {
                      this.DelIndex2 = this.DelIndex2;
                  } else {
                      this.DelIndex2 = this.DelIndex2 - 1;
                  }
              }
              this.$tool
                  .request({
                      url: "LIS/LIS1/LIS141",
                      method: "post",
                      data: {
                          action: action,
                          instrid: this.labinstrumentval,
                          interno: this.InstrItem.interno,
                      },
                  })
                  .then((res) => {
                      if (res.errcode == 1) {
                          this.$message({
                              message: "删除成功",
                              type: "success",
                          });
                          var delrow = this.$refs.xTable.getCurrentRow();
                          if (delrow) {
                              var alld = this.$refs.xTable.getTableData().fullData;
                              var rowindex = alld.indexOf(delrow);
                              this.$refs.xTable.remove(delrow).then(() => {
                                  this.tableData = this.$refs.xTable.tableFullData;

                                  setTimeout(async () => {
                                      let havedata = this.$refs.xTable.tableData;
                                      if (havedata.length > 0) {
                                          if (rowindex >= havedata.length) rowindex = havedata.length - 1;
                                          let selectrow = havedata[rowindex];
                                          this.$refs.xTable.setCurrentRow(selectrow);
                                          this.interno = selectrow.interno;
                                          this.tempinterno = selectrow.interno;
                                          this.InstrItem.interno = selectrow.interno;
                                          this.FindInstrData();
                                      }
                                  }, 5);
                              });
                          }
                      } else {
                          this.$message.error("删除失败:" + res.errmsg);
                      }
                  })
                  .catch((error) => {
                      console.log(error);
                  });
          } else if (action == "nulldel") {
              if (this.txtdelelinterno == "") {
                  this.$message({
                      message: "本单元下不存在未对应报告项目的数据",
                      type: "warn",
                  });
              } else {
                  this.$tool
                      .request({
                          url: "LIS/LIS1/LIS141",
                          method: "post",
                          data: {
                              action: action,
                              instrid: this.labinstrumentval,
                              delinternostr: this.txtdelelinterno,
                          },
                      })
                      .then((res) => {
                          if (res.errcode == 1) {
                              this.$message({
                                  message: "删除成功",
                                  type: "success",
                              });
                          } else {
                              this.$message.error("删除失败:" + res.errmsg);
                          }
                          this.FindInstrItem();
                          this.FindInstrData();
                      })
                      .catch((error) => {
                          console.log(error);
                      });
              }
          } else {
              var redata = {};
              if (action == "add")
                  redata = {
                      action: action,
                      instrid: this.labinstrumentval,
                      uptinfo: returnInstrItem,
                  };
              else {
                  // console.log("save2", returnInstrItem, this.tempInstrItem);
                  redata = {
                      action: action,
                      instrid: this.labinstrumentval,
                      interno: this.tempinterno,
                      uptinfo: returnInstrItem,
                      oldinfo: this.tempInstrItem,
                  };
              }
              this.$tool
                  .request({
                      url: "LIS/LIS1/LIS141",
                      method: "post",
                      data: redata,
                  })
                  .then((res) => {
                      if (res.errcode == 1) {
                          this.$message({
                              message: "保存成功",
                              type: "success",
                          });
                          if (this.actionflag == 1) this.NewArr.push(this.labinstrumentval + "");
                          else if (this.actionflag == 2) this.UpdateArr.push(this.labinstrumentval + "");
                          this.tableData = XEUtils.clone(this.$refs.xTable.tableFullData, true);
                          this.listSearch();
                      } else {
                          this.$message.error("保存失败:" + res.errmsg);
                      }
                      //this.FindInstrItem();
                      //this.tableData = this.$refs.xTable.afterFullData;
                      this.FindInstrData();
                  })
                  .catch((error) => {
                      console.log(error);
                  });
          }
      },
      SaveSeries() {
          var records = this.$refs.ResNum.getRecordset();
          var exrecord = this.GetReturnRecord(records);
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "savedilution",
                      instrid: this.labinstrumentval,
                      rpt_itemcode: this.InstrItem.rpt_itemcode,
                      urec: exrecord,
                  },
              })
              .then((res) => {
                  if (res.errcode == 1) {
                      this.$message({
                          message: "保存成功",
                          type: "success",
                      });
                  } else {
                      this.$message.error("保存失败:" + res.errmsg);
                  }
                  this.FindDilution();
              });
      },
      RptChangeEvent(code, name, row) {
          //this.InstrItem.rpt_itemcode = code;
          this.$nextTick(() => {
              this.$refs.inputrptitem.$refs.ddlrptitemSelect.focus();
          });
      },
      RptChange(val, row) {
          if (!val) {
              row.rptitemshow = -1;
              row.rpt_itemcode = "-1";
          }
      },
      CancelTips() {
          if (this.actionflag == "del") {
              this.DeldialogVisible = false;
          } else if (this.actionflag == "nulldel") {
              this.NullDeldialogVisible = false;
          } else {
              this.dialogif = false;
              this.dialogForm = false;
              for (var key in this.tempInstrItem) {
                  this.InstrItem[key] = this.tempInstrItem[key];
              }
          }
      },
      CommitTips() {
          if (this.actionflag == "del") {
              this.DeldialogVisible = false;
              this.tableInstrData = [];
              this.SaveRecord(this.actionflag);
          } else if (this.actionflag == "nulldel") {
              this.DelNullRpt();
              this.NullDeldialogVisible = false;
              this.tableInstrData = [];
              this.SaveRecord(this.actionflag);
              this.$nextTick(() => {
                  this.FindInstrItem();
                  this.$nextTick(() => {
                      this.FindInstrData();
                  });
              });
          } else {
              this.dialogif = false;
              this.dialogForm = false;
              this.SaveRecord(this.actionflag);
              this.$nextTick(() => {
                  this.FindInstrItem();
                  this.$nextTick(() => {
                      this.FindInstrData();
                  });
              });
          }
      },
      DelNullRpt() {
          let data = this.tempdata2;
          var filterdata = data.filter(function (e) {
              return e.rpt_itemcode == "" || e.rpt_itemcode == -1;
          });
          let res1 = "";
          if (data.length > 0) {
              filterdata.forEach((element) => {
                  //一个单引号换成两个，防止sql语句报错
                  element.interno = element.interno.replace(/'/g, "''");
                  if (res1 == "") {
                      res1 = "'" + element.interno + "'";
                  } else {
                      res1 += "," + "'" + element.interno + "'";
                  }
              });
          }
          this.txtdelelinterno = res1;
      },
      dualsort() {
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "autodual",
                      instrid: this.labinstrumentval,
                  },
              })
              .then((res) => {
                  this.AutodualVisible = false;
                  this.FindInstrItem();
              });
      },
      GetReturnRecord(records) {
          var exactArr = { insertRecords: [], removeRecords: [], updateRecords: [] };
          if (records.insertRecords.length > 0) {
              exactArr.insertRecords = this.GetoneRecords(records.insertRecords, 1);
          }
          if (records.removeRecords.length > 0) {
              exactArr.removeRecords = this.GetoneRecords(records.removeRecords, 1);
          }
          if (records.updateRecords.length > 0) {
              exactArr.updateRecords = this.GetoneRecords(records.updateRecords, 2);
          }
          return exactArr;
      },
      GetoneRecords(records, type) {
          var recordsarr = [];
          for (let i = 0, len = records.length; i < len; i++) {
              if (type == 1) {
                  var onerecord = this.GetOneRecord(records[i]);
                  recordsarr.push(onerecord);
              } else {
                  var onerecord = { odata: {}, cdata: {} };
                  onerecord.odata = this.GetOneRecord(records[i].odata);
                  onerecord.cdata = this.GetOneRecord(records[i].cdata);
                  recordsarr.push(onerecord);
              }
          }
          return recordsarr;
      },
      GetOneRecord(record) {
          var recordforreturn = {
              specimen_code: record.specimencode,
              instrid: this.labinstrumentval,
              rpt_itemcode: this.InstrItem.rpt_itemcode,
              result_ratio: record.result_ratio,
              result_add: record.result_add,
          };
          return recordforreturn;
      },
      SpecChange(code, row) {
          row.specimencode = code;
      },
      germchange(val) {
          if (!val) {
              if (this.showunitreqonly) {
                  this.myrptunitid = this.rptunitid;
              } else {
                  this.myrptunitid = "";
              }
          }
      },
      showunitchange(val) {
          if (val) {
              this.myrptunitid = this.rptunitid;
          } else {
              this.myrptunitid = "";
          }
      },
      dateChange() {
          if (this.$refs.xTable.getCurrentRow()) {
              this.FindInstrData();
          }
      },
      dualchange() {
          this.InstrItem.dual_useCH = this.InstrItem.dual_use == "1" ? "是" : "否";
      },
      autofocusEvent(event, element) {
          if (element == "inter") {
              this.$refs.inputrptitem.$refs.ddlrptitemSelect.focus();
          }
          if (element == "rptitem") {
              this.$refs.inputresratio.focus();
          }
          if (element == "ratio") {
              this.$refs.inputresadd.focus();
          }
          if (element == "add") {
              this.$refs.inputmethod.focus();
          }
          if (element == "method") {
              this.CommitTips();
          }
      },
      addrptitem(c, n, row) {
          this.tempRptItem.rptitemshow = row.itemcode_en + " " + n;
          this.tempRptItem.rpt_itemcode = c;
          this.InstrItem = this.tempRptItem;
          // var insertrow = this.$refs.xTable.getInsertRecords();
          // if (insertrow.length > 0 && insertrow.filter(item => item._XID == this.tempRptItem._XID).length > 0) {
          //     this.SaveRecord("add");
          // } else {
          //     this.SaveRecord("update");
          // }
          this.dialogRptVisible = false;
      },
      InternoChange({ row }, val) {
          this.InstrItem.interno = val.target.value;
          this.InternoRepeatCheck(this.InstrItem.interno);
          // var insertrow = this.$refs.xTable.getInsertRecords();
          // if (row.rpt_itemcode != "") {
          //     if (insertrow.length > 0 && insertrow.filter(item => item._XID == this.InstrItem._XID).length > 0) {
          //         this.SaveRecord("add");
          //     } else {
          //         this.SaveRecord("update");
          //     }
          // }
      },
      CopyInstr() {
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "copy",
                      sourceinstr: this.labinstrumentval,
                      targetinstr: this.targetinstrid,
                  },
              })
              .then((res) => {
                  if (res.errcode == "1") {
                      this.$message({
                          message: "复制成功",
                          type: "success",
                      });
                      this.FindInstrItem();
                      this.dialogCopyVisible = false;
                  } else {
                      this.$alert(res.errmsg, "错误");
                  }
              });
      },
      CopyShow() {
          this.dialogCopyVisible = true;
          var rows = this.$refs.instrinput.seloptions.filter((item) => item.instrid == this.labinstrumentval);
          if (rows.length > 0) this.copytoinstrid = rows[0].instrname;
          else this.copytoinstrid = this.labinstrumentval;
      },
      SaveUpdate() {
          var record = this.$refs.xTable.getRecordset();
          this.$tool
              .request({
                  url: "LIS/LIS1/LIS141",
                  method: "post",
                  data: {
                      action: "save",
                      urec: record,
                      instrid: this.labinstrumentval,
                  },
              })
              .then((res) => {
                  if (res.errcode == "1") {
                      this.$message({
                          message: "保存成功",
                          type: "success",
                      });
                      this.FindInstrItem();
                  } else {
                      this.$alert(res.errmsg, "错误");
                  }
              });
      },
      listSearch() {
          let filterName = this.searchtext.trim();
          if (filterName) {
              let filterRE = new RegExp(filterName, "gi");
              let num = this.AddArray;
              let rest = this.tableData.filter((item) => {
                  return item.interno.toUpperCase().indexOf(filterName.toUpperCase()) > -1 || (item.rptitemshow ? item.rptitemshow.toUpperCase().indexOf(filterName.toUpperCase()) > -1 : false) || item.interno == num;
              });
              this.list = XEUtils.clone(rest, true);
          } else {
              this.list = XEUtils.clone(this.tableData, true);
          }
      },
      ImportFile() {
          this.$rm_uploadFiles({
              type: "文件上传",
              prgname: "LIS141",
              param1: this.labinstrumentval,
              btn: {
                  confirmBtnText: "立即上传",
                  cancelBtnText: "取消",
              },
          })
              .then((res) => {
                  if (res.flag == "1") {
                      this.$notify.success({
                          title: "成功",
                          message: `文件上传成功`,
                      });
                      this.FindInstrItem();
                  } else {
                      this.$notify.error({
                          title: "错误",
                          message: `文件上传失败`,
                      });
                  }
              })
              .catch((e) => {
                  console.log("error", e);
              });
      },
      ExportFile() {
          let columns = this.$refs.xTable.getTableColumn().tableColumn;
          let exportcolumn = [];
          for (let i = 0; i < columns.length; i++) {
              if (columns[i].property != "stopflag" && columns[i].property != "lastusetime") exportcolumn.push({ field: columns[i].property, title: columns[i].title });
          }
          exportcolumn.push({ field: "rpt_itemcode", title: "项目代码" });
          let datas = XEUtils.clone(this.tableData, true);

          this.$pub.exportTableExcel(datas, exportcolumn, "LIS141仪器通道号.xlsx");

          // var p = { prgno: "LIS141", instrid: this.labinstrumentval, style: "dat" };
          // this.$pub.commexport(this, p, `仪器通道号.dat`);
      },
      //新增时通道号重复检查
      InternoRepeatCheck(val) {
          var row = this.$refs.xTable.getCurrentRow();
          //判断当前行是新增行还是已有行
          var addflag = false;
          if (!this.InstrItem._XID) addflag = true;
          let data = this.$refs.xTable.tableFullData;
          if (data.length > 1) {
              let fdata = data.filter((m) => m.interno == val);
              if (!!fdata && fdata.length > (addflag ? 0 : 1)) {
                  this.$alert("该通道号重复录入，请重新输入！", "错误").then(() => {
                      row.interno = "";
                      this.$refs.xTable.setActiveCell(row, "interno");
                  });
              }
          }
      },
  },
  beforeRouteEnter(to, from, next) {
      next((vm) => {
          // 通过 `vm` 访问组件实例
          let that = vm;
          document.onkeydown = function (e) {
              let key = window.event.keyCode;
              //65到90 a到z（A到Z）
              //112到135 F1到F24
              if (key == 116) {
                  //（F5）查询
                  that.FindInstrItem();
              }
              else if (key == 117) {
                  //（F6）新增
                  that.OpenDialog('add');
              }
              else if (key == 114) {
                  //（F3）删除
                  that.OpenDialog('del');
              }
              else if (key == 119) {
                  //（F8）保存
                  that.SaveUpdate();
              }
          };
      });
  },
  watch: {
      labinstrumentval(oldval, newval) {
          if (this.FirstLoadingItem) {
              this.FindInstrItem(newval);
              this.FindInstrData(newval);
          }
      },
  },
};
</script>

<style scoped>
::v-deep .Update {
  color: #5050fa;
}
::v-deep .Add {
  color: #b47c7c;
}
::v-deep .DualRow {
  background-color: #e9b1b1;
}
::v-deep .el-input.is-disabled .el-input__inner {
  color: black;
}
::v-deep .el-checkbox.is-disabled .el-checkbox__label {
  color: black;
}
::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: black;
}
::v-deep .vxe-button--wrapper {
  width: 100%;
}
.pagetop {
  left: 0;
  right: 0;
  height: 76px;
  display: -webkit-box;
  -webkit-box-pack: center;
  -webkit-box-align: center;
  border: solid 1px #ccc;
  position: absolute;
  z-index: 99;
}

.pagecenter {
  position: absolute;
  top: 80px;
  width: 100%;
  left: 0;
  bottom: 0px;
}

.middle-center {
  position: absolute;
  height: 100%;
  left: 645px;
  right: 0;
}

.middle-left {
  position: absolute;
  height: 100%;
  width: 640px;
  left: 0px;
  top: 0;
}

table tr td:nth-child(odd) {
  text-align: right;
  line-height: 32px;
  white-space: nowrap;
}
table tr td:nth-child(even) {
  text-align: left;
}
table {
  font-size: 12px;
}
td {
  padding: 0 5px 0 0;
}
::v-deep .el-checkbox__inner::after {
  border: 2px solid #000000 !important;
  box-sizing: content-box;
  content: "";
  border-left: 0 !important;
  border-top: 0 !important;
  height: 7px;
  left: 4px;
  position: absolute;
  top: 1px;
  transform: rotate(45deg) scaleY(0);
  width: 3px;
  transition: transform 0.15s ease-in 0.05s;
  transform-origin: center;
}
::v-deep .el-checkbox__input.is-disabled + span.el-checkbox__label {
  color: #000000;
  cursor: not-allowed;
}
::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner,
.el-checkbox__input.is-disabled.is-checked .el-checkbox__inner + .el-input.is-disabled .el-input__inner {
  background-color: #ffffff !important;
}
::v-deep .el-input--suffix .el-input__inner {
  padding-right: 0px;
}
::v-deep .vxe-table .el-input--mini .el-input__inner {
  height: 24px;
  line-height: 24px;
}
::v-deep tr.vxe-body--row.row-modify {
  color: blue;
}
::v-deep tr.vxe-body--row.row-new {
  color: #cc6600;
}
</style>
